package com.nosnow.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nosnow.common.utils.R;
import com.nosnow.edu.entity.EduVideo;
import com.nosnow.edu.invoking.VodClient;
import com.nosnow.edu.mapper.EduVideoMapper;
import com.nosnow.edu.service.EduVideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nosnow.handler.SnowflakeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author bingheng
 * @since 2020-04-04
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {

    @Autowired
    private VodClient vodClient;

    @Override
    public void removeVideoByVideoId(String id) {
        // 1. 根据小节Id，查询出视频Id
        EduVideo eduVideo = baseMapper.selectById(id);

        // 2. 根据视频Id，删除阿里云端的视频，远程调用vod模块
        if(!StringUtils.isEmpty(eduVideo.getVideoSourceId())) {
            R result = vodClient.removeAlyVideo(eduVideo.getVideoSourceId());

            // 2.1 采用熔断机制，如果删除云端视频失败，则抛出如下异常
            if(result.getCode() == 20001){
                throw new SnowflakeException(20001, result.getMessage());
            }
        }
    }

    @Override
    public void removeVideoByCourseId(String courseId) {
        // 1. 根据课程Id查询该课程中所有的视频Id
        QueryWrapper<EduVideo> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", courseId);
        wrapper.select("video_source_id"); // 指定要查询的列，这里只需要查询出视频Id的集合即可
        List<EduVideo> eduVideos = baseMapper.selectList(wrapper);

        // 2. 遍历得到视频Id集合
        List<String> videoIds = new ArrayList<>();
        if(eduVideos != null && !eduVideos.isEmpty()){
            eduVideos.forEach(o -> {
                if(!StringUtils.isEmpty(o.getVideoSourceId())) {
                    videoIds.add(o.getVideoSourceId());
                }
            });
        }

        // 3. 调用视频模块接口，删除阿里云端视频
        if(!videoIds.isEmpty()) {
            R result = vodClient.removeAlyVideos(videoIds);
            if(result.getCode() == 20001){
                throw new SnowflakeException(20001, result.getMessage());
            }
        }

        // 4. 删除小节
        baseMapper.delete(wrapper);
    }

    @Override
    public void updateVideoById(String id) {
        EduVideo eduVideo = new EduVideo();
        eduVideo.setId(id);
        eduVideo.setVideoSourceId("");
        eduVideo.setVideoOriginalName("");
        baseMapper.updateVideoById(eduVideo);
    }
}
